﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace tomvangaever.CorrelationWebPart.CorrelationViewWebPart
{
    public partial class CorrelationViewWebPartUserControl : UserControl
    {
        private const string SORTDIRECTION = "SortDirection";
        private const string SORTEXPRESSION = "SortExpression";
        private const string CORRELATIONID = "correlationid";
        private const string MON_PAGELOAD = "CorrelationViewWebPartUserControl Page_Load";

        public static DataView _ullogs;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if(string.IsNullOrEmpty(txtCorrelationID.Text))
                    txtCorrelationID.Text = Request.QueryString[CORRELATIONID];
                RunInMonitoredScope(BuildCorrelationGrid, MON_PAGELOAD);
                ulsgrid.Visible = true;
            }
            catch (Exception ex) {
                ulsgrid.Visible = false;
                lblError.Text = ex.ToString();
            }
        }

        private void BuildCorrelationGrid()
        {
            if (IsPostBack)
            {
                string correlationtoken = txtCorrelationID.Text;
                bool isValidCorrelationTaken = true;
                isValidCorrelationTaken = !string.IsNullOrEmpty(correlationtoken);
                if (isValidCorrelationTaken)
                {
                    Guid correlation = new Guid(correlationtoken);
                    var logs = SPCorelationIDService.GetLogs(correlation);
                    _ullogs = logs;
                    if (ViewState[SORTDIRECTION] != null && ViewState[SORTEXPRESSION] != null)
                    {
                        _ullogs.Sort = ViewState[SORTDIRECTION].ToString() + " " + ViewState[SORTEXPRESSION].ToString();
                    }
                    ulsgrid.DataSource = _ullogs;
                    ulsgrid.DataBind();
                }
            }
        }

        private void RunInMonitoredScope(Action action, string monitoredScopeName)
        {
            using (SPMonitoredScope scope = new SPMonitoredScope(monitoredScopeName))
            {
                action();
            }
        }

        protected void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ulsgrid.PageIndex = e.NewPageIndex;
            ulsgrid.DataBind();
        }

        protected void UseCurrentCorrelationID_Clicked(object sender, EventArgs e) {
            txtCorrelationID.Text = CorrelationId.GetCurrentCorrelationToken().ToString();
        }
    }
}
